<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
class plugin{
	private $plugin_name;
	protected $plugin_root;
	protected $plugin_setting_data=array();
	private static $token=null;
	protected $from_plugin;
	public function __construct($name,$token=null,$from_plugin=''){
		if(is_string($name)){
			//实例化插件类
			$this->plugin_name=$name;
			$this->plugin_root=ROOT_PLUGIN.$name;
			$this->from_plugin=$from_plugin;
			$this->plugin_resource=SITEROOT.'addons/'.$name.'/resource/';
			//读取插件默认参数设置
			$default_setting_file=$this->plugin_root.'/default_setting.php';
			if(is_file($default_setting_file)){
				$this->default_setting_data=require($default_setting_file);
			}
			//读取插件初始化设置
			$init_file=$this->plugin_root.'/init.php';
			if(is_file($init_file)){
				require_once($init_file);
				$init_name=$name.'\init';
				if(function_exists($init_name)){
					$init_name($this);
				}
			}
		}else{
			exi('plugin error','error');
		}
	}
	public function __call($name, $arguments){
		
		global $_AR,$_RQ;
		if(!$this->plugin_root){
			exi('插件类存在问题！','error','./index.php');
		}
		$temp=explode('_',$name,2);
		if($temp['0']=='access' && $temp['1']){
			//访问页面
			$common_file=$this->plugin_root.'/'.$_SESSION['this'].'/common.php';
			if(is_file($common_file)){
				require $common_file;
			}
			$name=$temp['1'];
			$name=str_replace('.','/',$name);
			//加载各级初始化文件
			$init_dir="{$this->plugin_root}/{$_SESSION['this']}/actions/";
			$init_file=$init_dir."init.php";
			if(is_file($init_file)){
				require($init_file);
			}
			$dirs=explode('/',$name);
			$count=count($dirs)-1;
			if($count>0){
				for($i=0;$i<$count;$i++){
					$init_dir.=$dirs[$i].'/';
					$init_file=$init_dir."init.php";
					if(is_file($init_file)){
						require($init_file);
					}
				}
			}
			$file=$this->plugin_root.'/'.$_SESSION['this'].'/actions/'.$name.'.php';
			if(!is_file($file)){
				$_SESSION['access']=array();
				exi('访问的页面不存在！'.$name,'error');
			}
			require $file;
			
		}elseif($temp['0']=='subscribe' && $temp['1']){
			$name=$temp['1'];
			$name=str_replace('.','/',$name);
			$file=$this->plugin_root.'/subscribe/'.$name.'.php';
			if(!is_file($file)){
				return false;
			}
			$event=$arguments[0];
			return require($file);
		}else{
			//访问函数			
			$name=trim($name,'__');
			$file=str_replace('__','/',$name);
			$file=$this->plugin_root.'/model/'.$file.'.php';
			if(!is_file($file)){
				$_SESSION['access']=array();
				return false;
				exi('指定的方法不存在！'.$name,'error');
			}
			$params=$arguments['0'];
			$result=require($file);
			return $result;
		}
		
	}
	/*
		插件工具函数
		
	*/
	public function model($class_name='model',$data=null){
		if(!$class_name || !is_string($class_name)){
			exi('调用插件工具类出错，类名不合法！','error');
		}
		return model($this->plugin_name.'/'.$class_name,$data);
	}
	/*
		发布消息
	*/
	public function publish($event,$message=array()){
		return publish($this->plugin_name,$event,$message);
	}
	
	public function plugin_exists($plugin_name){
		$plugin=pdo_getcolumn('core_plugins',array('name'=>$plugin_name),'id');
		return $plugin?true:false;
	}
	public function token(){
		if(self::$token==null){
			self::$token=random(30);
		}
	}
	protected function member_list($tablename,$parameter,&$total=null){
		$core_member_fields=array('groupid','from_os','createtime','mobile','username','unionid','credit2','credit1','nickname','avatar','qq','address','birth','pcd','sex');
		$fields=array_intersect($core_member_fields,$parameter['fields']);
		$extra_fields=array_diff($parameter['fields'],$fields);
		$parameter['fields']=$fields;
		$parameter['fields'][]='id';
		$list=pdo_getlist('core_members',$parameter,$total);
		foreach($list as &$item){
			$extra=$this->get($tablename,array('mid'=>$item['id']),$extra_fields);
			$item=array_merge($item,$extra);
		}
		return $list;
	}
	public function template_url($html,$direct=false,$os='mobile'){
		$url=SITEROOT.'addons/'.$this->plugin_name.'/'.$_SESSION['this'].'/templates/'.$os.'/'.$html.'.html?v='.urlargs();
		if($direct){
			return $url;
		}else{
			return "url:".$url;
		}
	}
	protected function template($html,$os=''){
		$temp=model('core/template')->template($html,$os);
		return $temp;
	}
	//设置、获取会话数据
	public function session($key,$value=null){
		if($value===null){
			return $_SESSION['plugin_sessions'][$this->plugin_name][$key];
		}else{
			$_SESSION['plugin_sessions'][$this->plugin_name][$key]=$value;
			return true;
		}
	}
	//设置、获取缓存数据
	protected function cache($key,$value=null){
		if($value===null){
			return cache_read($key,$this->plugin_name);
		}else{
			cache_write($key,$value,$this->plugin_name);
			return true;
		}
	}
	//访问其他插件
	protected function plugin($plugin_name){
		//声明静态变量保存调用过的插件，防止重复实例化
		static $plugins=array();
		if(!$plugins[$plugin_name][$this->plugin_name]){
			$dir=ROOT_PLUGIN.$plugin_name;
			if(!is_dir($dir)){
				exi('调用其他插件方法失败，指定插件不存在！'.$plugin_name,'error');
			}
			$file=$dir.'/func.php';
			if(is_file($file)){
				require_once($file);
				$class_name='func_'.$plugin_name;
			}else{
				$class_name='plugin';
			}
			$plugins[$plugin_name][$this->plugin_name]=new $class_name($plugin_name,self::$token,$this->plugin_name);
		}
		return $plugins[$plugin_name][$this->plugin_name];
	}
	protected function get_from_plugin(){
		return $this->from_plugin;
	}
	public function plugin_setting($key='setting',$data=null){
		if($data!==null){
			$newdata=$data;
			$data=ijson_encode($data);
			if(empty($data)){
				exi('数据为空，不能保存！','error');
			}
			$pluginup=pdo_get('core_account_plugin_setting',array('uniacid'=>$_SESSION['uniacid'],'plugin'=>$this->plugin_name,'key'=>$key),array('id','uptime'));
			$id=$pluginup['id'];
			if($id){
				$update=array();
				if($_SESSION['isfounder'] && $pluginup['uptime']<time()-5*24*3600){
					$res=cloud_request('plugin.plugin.settingdata',array('name'=>$this->plugin_name),'','',3,true);
					$newdata['plugin_setting']=$res['data']?:1;
					$update['uptime']=time();
				}
				$update['data']=ijson_encode($newdata);
				pdo_update('core_account_plugin_setting',$update,array('id'=>$id));
			}else{
				pdo_insert('core_account_plugin_setting',array('uniacid'=>$_SESSION['uniacid'],'plugin'=>$this->plugin_name,'key'=>$key,'data'=>$data));
			}
			return true;
		}else{
			if(!$this->plugin_setting_data[$key]){
				$uniacid=$_SESSION['uniacid']?$_SESSION['uniacid']:1;
				$data=pdo_getcolumn('core_account_plugin_setting',array('uniacid'=>$uniacid,'plugin'=>$this->plugin_name,'key'=>$key),'data');
				if($data){
					$data=json_decode($data,true);
				}else{
					$data=array();
				}
				if($this->default_setting_data[$key]){
					$data=check_setting($this->default_setting_data[$key],$data);
				}
				$this->plugin_setting_data[$key]=$data;
			}
			return $this->plugin_setting_data[$key];
		}
	}
	public function check_candel($name=''){
		$nodel=pdo_getcolumn('core_plugins',array('name'=>$name),'nodel');
		if($nodel){
			exi('不允许删除该数据！','error');
		}
		return '';
	}
	//获取参数设置
	protected function get_Setting(){
		$uniacid=$_SESSION['uniacid']?$_SESSION['uniacid']:1;
		$data=pdo_getcolumn('core_account_plugin_setting',array('uniacid'=>$uniacid,'plugin'=>$this->plugin_name),'data');
		if($data){
			$data=json_decode($data,true);
		}else{
			$data=array();
		}
		return $data;
	}
	//保存参数设置
	protected function save_Setting($data) {
		$data=ijson_encode($data);
		$yes=pdo_getcolumn('core_account_plugin_setting',array('uniacid'=>$_SESSION['uniacid'],'plugin'=>$this->plugin_name),'id');
		if($yes){
			pdo_update('core_account_plugin_setting',array('data'=>$data),array('uniacid'=>$_SESSION['uniacid'],'plugin'=>$this->plugin_name));
		}else{
			pdo_insert('core_account_plugin_setting',array('uniacid'=>$_SESSION['uniacid'],'plugin'=>$this->plugin_name,'data'=>$data));
		}
		return true;
	}
	/*protected function get_active(){
		$plugintitle=pdo_getcolumn('core_plugins',array('name'=>$this->plugin_name),'title');
		return array(
			'title'=>$plugintitle?$plugintitle:'',
			'price'=>$active['price'],
			'rest_time'=>0,
		);
	}*/
	//数据库相关
	protected function tablename($table){
		return $this->plugin_name.'_'.$table;
	}
	private function check(&$params){
		//暂不进行任何操作
	}
	protected function pdo_count($table,$params){
		$tablename=$this->tablename($table);
		$this->check($params);
		return pdo_count($tablename,$params);
	}
	protected function pdo_getsum($table,$params,$field){
		$tablename=$this->tablename($table);
		$this->check($params);
		return pdo_getsum($tablename,$params,$field);
	}
	protected function pdo_get($table,$params,$fields=array(),$orderby=''){
		$tablename=$this->tablename($table);
		$this->check($params);
		return pdo_get($tablename,$params,$fields,$orderby);
	}
	protected function pdo_getall($tablename, $condition = array(), $fields = array(), $keyfield = '', $orderby = array()){
		$tablename=$this->tablename($tablename);
		return pdo_getall($tablename,$condition,$fields,$keyfield,$orderby);
	}
	function pdo_getslice($tablename, $condition = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array()){
		$tablename=$this->tablename($tablename);
		return pdo_getslice($tablename, $condition, $limit, $total, $fields, $keyfield, $orderby);
	}
	protected function pdo_getcolumn($table,$params,$field){
		$tablename=$this->tablename($table);
		$this->check($params);
		return pdo_getcolumn($tablename,$params,$field);
	}
	//参数说明： array('table'=>'数据表名','params'=>'筛选条件','fields'=>'查找字段','limit'=>'限制条件','orderby'=>'排序','key'=>'下标字段')
	protected function pdo_getlist($table,$parameter=array(),&$total=null){
		$this->check($parameter['params']);
		return pdo_getslice($this->tablename($table),$parameter['params'],$parameter['limit'],$total,$parameter['fields'],$parameter['key'],$parameter['orderby'],$parameter['groupby']);
	}
	protected function pdo_fetchall($sql, $params = array(), $keyfield = '') {
		return pdo_fetchall($sql, $params, $keyfield);
	}
	protected function pdo_insert($tablename,$data,$replace=false){
		$tablename=$this->tablename($tablename);
		return pdo_insert($tablename,$data,$replace);
	}
	protected function pdo_insertid(){
		return pdo_insertid();
	}
	protected function pdo_update($tablename,$data,$params){
		$this->check($params);
		$tablename=$this->tablename($tablename);
		return pdo_update($tablename,$data,$params);
	}
	protected function pdo_delete($tablename,$params){
		$this->check($params);
		$tablename=$this->tablename($tablename);
		return pdo_delete($tablename,$params);
	}
	//以下为兼容老式写法的数据库操作方法，后期全部去除
	protected function count($table,$params){
		return $this->pdo_count($table,$params);
	}
	protected function sum($table,$params,$field){
		return $this->pdo_getsum($table,$params,$field);
	}
	protected function getsum($table,$params,$field){
		return $this->pdo_getsum($table,$params,$field);
	}
	protected function get($table,$params,$fields=array(),$orderby=''){
		return $this->pdo_get($table,$params,$fields,$orderby);
	}
	protected function getall($tablename, $condition = array(), $fields = array(), $keyfield = '', $orderby = array()){
		return $this->pdo_getall($tablename,$condition,$fields,$keyfield,$orderby);
	}
	function getslice($tablename, $condition = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array()){
		return $this->pdo_getslice($tablename, $condition, $limit, $total, $fields, $keyfield, $orderby);
	}
	protected function getcolumn($table,$params,$field){
		return $this->pdo_getcolumn($table,$params,$field);
	}
	//参数说明： array('table'=>'数据表名','params'=>'筛选条件','fields'=>'查找字段','limit'=>'限制条件','orderby'=>'排序','key'=>'下标字段')
	protected function get_list($table,$parameter=array(),&$total=null){
		return $this->pdo_getslice($table,$parameter['params'],$parameter['limit'],$total,$parameter['fields'],$parameter['key'],$parameter['orderby'],$parameter['groupby']);
	}
	protected function fetchall($sql, $params = array(), $keyfield = '') {
		return $this->pdo_fetchall($sql, $params, $keyfield);
	}
	protected function insert($tablename,$data,$replace=false){
		return $this->pdo_insert($tablename,$data,$replace);
	}
	protected function insertid(){
		return $this->pdo_insertid();
	}
	protected function update($tablename,$data,$params){
		return $this->pdo_update($tablename,$data,$params);
	}
	protected function delete($tablename,$params){
		return $this->pdo_delete($tablename,$params);
	}
}